package com.dxjd.multi_camera_plugin

import android.content.Context
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.camera.view.PreviewView
import io.flutter.plugin.platform.PlatformView

/**
 * 相机预览视图
 *
 * 简洁的预览视图实现，依赖 NativeCameraManager 提供正确方向的图像流
 */
class CameraPreviewView(
    private val context: Context,
    id: Int,
    creationParams: Map<String?, Any?>?
) : PlatformView {

    private val previewView: PreviewView
    private var nativeCameraManager: NativeCameraManager? = null
    private var isCircular: Boolean = false

    init {
        previewView = PreviewView(context)
        previewView.scaleType = PreviewView.ScaleType.FILL_CENTER

        // 设置布局参数
        previewView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )

        if (creationParams != null) {
            isCircular = creationParams["isCircular"] as? Boolean ?: false
        }

        val cameraManager = MultiCameraPlugin.getCurrentCameraManager()
        if (cameraManager != null) {
            this.nativeCameraManager = cameraManager
            cameraManager.bindPreview(previewView)
            
            // 设置显示方向
            previewView.post {
                val rotation = previewView.display?.rotation
                if (rotation != null) {
                    Log.d("CameraPreviewView", "设置显示旋转: $rotation")
                    cameraManager.setTargetRotation(rotation)
                }
            }
        }
    }

    override fun getView(): View {
        return previewView
    }

    override fun dispose() {
        Log.d("CameraPreviewView", "Disposing CameraPreviewView")
    }
}

/**
 * PlatformView工厂类
 */
class CameraPreviewViewFactory : io.flutter.plugin.platform.PlatformViewFactory(
    io.flutter.plugin.common.StandardMessageCodec.INSTANCE
) {
    override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
        val creationParams = args as? Map<String?, Any?>
        return CameraPreviewView(context, viewId, creationParams)
    }
}

